import { defineStore } from 'pinia'
import request from '@/utils/request'
import { apiRes, categoryItem, SubCategory, TopCategory } from '@/types/data'
import { topCategory } from '../constants'

const defaultCategory = topCategory.map(item => ({name: item}))
export default defineStore('category', {
  state: () => ({
    lsit: defaultCategory as categoryItem[],
    topCategory: {} as TopCategory,
    subCategory: {} as SubCategory
  }),
  actions: {
    async getAllCategory() {
      const res = await request.get<apiRes<categoryItem[]>>('/home/category/head')
      res.data.result.forEach(item => item.open = false)
      this.lsit = res.data.result
    },
    show(id: string) {
      // 找到对应 id 的元素, 将状态改为 true
      const item = this.lsit.find(item => item.id === id)
      // if(item) {
      //   item.open = true
      // }
      item!.open = true
    },
    hide(id: string) {
      const item = this.lsit.find(item => item.id === id)
      // if(item) {
      //   item.open = false
      // }
      item!.open = false
    },
    async getTopCategory(id: string) {
      const res = await request.get<apiRes<TopCategory>>('/category', {
        params: {
          id
        }
      })
      this.topCategory = res.data.result
    },
    async getSubCategory(id: string) {
      const res = await request.get<apiRes<SubCategory>>('/category/sub/filter', {
        params: {
          id
        }
      })
      this.subCategory = res.data.result
    },
    resetSubCategory() {
      this.subCategory = {} as SubCategory
    }
  }
})